import 'dart:math';

import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:saas_order_meal/res/resources.dart';
import 'package:saas_order_meal/saas_order_meal.dart';
import 'package:saas_order_meal/utils/meal_ext_utils.dart';
import 'package:saas_order_meal/viewmodel/regular_menu_contain_view_model.dart';

import '../model/customer_info_model.dart';
import '../model/order_request_data.dart';
import '../model/week_food_model.dart';
import '../net/net_response/fee_rule_data.dart';

class ApplyMealViewModel extends BaseViewModel {
  final OrderRequestData orderRequestData;
  late OrderRequestData orderData;

  ApplyMealViewModel(BuildContext? context, {required this.orderRequestData})
      : super(context) {
    orderData = orderRequestData.copyWith();
  }

  var model = WeekFoodModel();
  var customerModel = CustomerInfoModel();
  var msg = "";
  var count = 0;

  num totalPrice = 0;
  num payPrice = 0;

  var freeMenuType = <dynamic>[];

  Future<void> getFeeRule() async {
    showLoadingDialog();
    try {
      var rule = await model.getFeeRule(orderData.elderHumanId);
      hideDialog();
      freeMenuType = (rule.menuTypeRuleInfoList ?? [])
          .takeWhere<MenuTypeRuleInfoList>((e) => e.moneyFlag == 0)
          .map((e) => e.menuTypeId)
          .toList();
      print(freeMenuType);
      calculateTotal();
    } catch (e) {
      hideDialog();
      showToast(e.toNetError());
    }
  }

  void calculateTotal() {
    payPrice = 0.0;
    totalPrice = 0.0;
    for (var item in orderData.selectFood) {
      var price = item.price;
      var limit = orderData.limitMap![item.timeSection];
      totalPrice += max(price - (limit ?? 0), 0);
    }

    if (freeMenuType.contains(orderData.menuTypeId)) {
      payPrice = 0.0;
    } else {
      payPrice = totalPrice;
    }
    // debugPrint("pryPrice====>${orderData.menuTypeId}");
    notifyListeners();
  }


  Future<void> submitOrderClick() async {
    if(SaasOrderMeal.needCheckRemain){
      var remain = await _getAccountRemain();
      if(SaasOrderMeal.enableBelowZeroPay){
        if(remain<0){
          showApplyDialog("当前余额:¥${remain}\n是否继续点餐",onApplyClick: (){
            submitOrder();
          });
        }else{
          submitOrder();
        }
      }else{
        if(remain<payPrice){
          if(SaasOrderMeal.enableNoRemainPay){
            showApplyDialog("当前余额不足:¥${remain}\n是否继续点餐",onApplyClick: (){
              submitOrder();
            });
          }else{
            showApplyDialog("当前账户余额不足",canApply: false);
          }
        }else{
          submitOrder();
        }
      }

    }else{
      submitOrder();
    }
  }

  Future<void> submitOrder() async {
    count = 0;
    // showToast(orderData.useType.toString())
    // return;
    var list = orderData.selectFood;

    showLoadingDialog(msg: "正在提交中");
    try {
      var recordCodes = <String>[];
      var price = 0.0;
      for (var meal in list) {
        var codeMap = await submitMeal(meal);
        var code = codeMap['orderCode'];
        recordCodes.add(code);
        var payPrice = codeMap['actualMoney'] as num;
        price += payPrice;
        var remain = codeMap['remain'];
        var giftRemain = codeMap['giftRemain'];
        if (count >= orderData.selectFood.length) {
          hideDialog();
          showSuccessDialog(
              payPrice: payPrice,
              remain: remain,
              giftRemain: giftRemain,
              recordCodes: recordCodes);
        }
      }
    } catch (e) {
      print(e);
      showToast(e.toNetError());
      hideDialog();
    }
  }

  void showSuccessDialog(
      {required num payPrice,
      required num remain,
      required num giftRemain,
      required List<String> recordCodes}) {
    showCupertinoDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) {
          return WillPopScope(
              child: CupertinoAlertDialog(
                content: Column(
                  children: [
                    Image.asset(
                      'images/icon_success.png',
                      package: 'saas_order_meal',
                    ),
                    Container(
                      height: 10,
                    ),
                    CommonText('支付成功'),
                    Container(
                      height: 10,
                    ),
                    CommonText('原价：¥${orderRequestData.totalPrice}'),
                    Container(
                      height: 10,
                    ),
                    CommonText('实付：¥${payPrice}'),
                    Container(
                      height: 10,
                    ),
                    CommonText('卡内余额：¥$remain'),
                    if (SaasOrderMeal.showGiftRemain) ...[
                      Container(
                        height: 10,
                      ),
                      CommonText('福利余额：¥$giftRemain'),
                    ]
                  ],
                ),
                actions: [
                  TextButton(
                      onPressed: () {
                        Go().pop();
                        Go().pop(result: "true");
                      },
                      child: CommonText('关闭')),
                  if (SaasOrderMeal.needPrint)
                    TextButton(
                        onPressed: () {
                          if (SaasOrderMeal.onPrintClickListener != null) {
                            SaasOrderMeal.onPrintClickListener!(recordCodes);
                          }
                        },
                        child: CommonText('打印小票'))
                ],
              ),
              onWillPop: () {
                return Future(() => false);
              });
        });
  }

  Future<Map<String, dynamic>> submitMeal(SelectFoodData meal) async {
    count++;
    var orderCode = "";
    var map = <String, dynamic>{};
    if (!meal.hasSubmit) {
      var goodsList = meal.selectFood
          .map((e) => {"goodsId": e.goodsId, "num": e.number, "price": e.price})
          .toList();
      var data = await model.submitWeekByMeal(
          elderHumanId: orderData.elderHumanId,
          userRoomId: orderData.userRoomId,
          siteId: orderData.siteId,
          useAddr: orderData.siteName ?? "",
          goodsList: goodsList,
          useDate: orderData.date ?? "",
          totalMoney: meal.price,
          useType: orderData.useType,
          useTimeSection: meal.timeSection,
          menuId: orderData.menuId,);
      meal.hasSubmit = true;
      var orderId = data['data']['id'].toString();
      meal.orderId = orderId;
    }

    if (!meal.hasPaid) {
      var payResult = await model.oneCardPay(
          orderId: meal.orderId,
          totalMoney: meal.price.toString(),
          actualMoney: payPrice.toString());
      orderCode = payResult['data']['orderCode'] ?? "";
      map['orderCode'] = orderCode;
      map["remain"] = payResult['data']["balMoney"] ?? 0.0;
      map['giftRemain'] = payResult['data']["benfitBalMoney"] ?? 0.0;
      map['actualMoney'] = payResult['data']["actualMoney"] ?? 0.0;
    }
    return map;
  }

  @override
  void onCreated() {
    super.onCreated();
    calculateTotal();
    if (SaasOrderMeal.needFeeRule) {
      getFeeRule();
    }
  }

  Future<double> _getAccountRemain() async {
   var data = await customerModel.getCardAccount(humanId: orderData.elderHumanId);
   return (data.acct?.balMoney??0.0)+(data.acct?.benfitBalMoney??0.0);
  }


  void showApplyDialog(String message,{bool canApply = true,Function()? onApplyClick}){
    showDialog(context: context, builder: (context){
      return Dialog(
        backgroundColor: Colors.transparent,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            SizedBox(height: 20,),
            CommonText(message),
            SizedBox(height: 20,),
            
            Row(
              children: [
                Container(),
                TextButton(onPressed: (){
                  Go().pop();
                }, child: CommonText('取消',textColor: Colors.grey),style: TextButton.styleFrom(
                  shape: StadiumBorder()
                ),).setWeight(1),
                if(canApply)
                TextButton(onPressed: (){
                  Go().pop();
                  if(onApplyClick!=null){
                    onApplyClick();
                  }
                }, child: CommonText('确定',textColor: Colors.white),style: TextButton.styleFrom(
                  shape: StadiumBorder(),backgroundColor: Colors.blue
                ),).setWeight(1),
                Container(),
              ].insertWidget(SizedBox(width: 16,)),
            ),
            SizedBox(height: 15,)
          ],
        ).addToContainer(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: 6.borderRadius
          )
        ),
      );
    },barrierDismissible: false);
  }
}
